﻿using AutoMapper;
using IMES.Common.Domain.DariusModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;

namespace Darius.API.Application.Commands
{
    public class PermissionsCreateHandler : IRequestHandler<PermissionsCreateCommand, Result>
    {
        private readonly IBaseRepositorys<Permission> permissionsRepository;
        private readonly IMapper mapper;
        private readonly ILogger<Permission> logger;

        public PermissionsCreateHandler(IBaseRepositorys<Permission> permissionsRepository, IMapper mapper, ILogger<Permission> logger)
        {
            this.permissionsRepository = permissionsRepository;
            this.logger = logger;
            this.mapper = mapper;
        }
        /// <summary>
        /// 权限添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(PermissionsCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new Result() { Code = (int)CodeEnum.add };
                Permission permission=mapper.Map<Permission>(request);
                var list= permissionsRepository.Add(permission);
                if (list > 0)
                {
                    result.Messege = "添加权限成功";
                    result.Code = list;
                }
                else
                {
                    result.Messege = "添加权限失败";
                    result.Code = -1;
                }
                logger.LogInformation(result.Messege);
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "添加权限失败");
                return new Result() { Code = (int)CodeEnum.error, Messege = "添加权限失败" };             
            }
            
        }
    }
}
